<template>
  <view class="poi-map-container">
    <!-- 搜索组件 -->
    <POISearch 
      :customPOIs="customPOIs" 
      @select-poi="handleSelectPOI"
      @search-complete="handleSearchComplete"
    />
    
    <!-- 返回按钮 -->
    <view class="back-btn" @click="goBack">
      <text class="iconfont icon-back">←</text>
    </view>
    
    <!-- 地图区域 -->
    <view class="map-wrap">
      <view id="mapContainer" class="map-container"></view>
      
      <!-- 地图加载中提示 -->
      <view class="map-loading" v-if="!isMapLoaded">
        <text class="loading-text">地图加载中...</text>
      </view>
      
      <!-- 地图加载错误提示 -->
      <view class="map-error" v-if="mapError">
        <text class="error-text">{{ mapError }}</text>
        <button class="retry-btn" @click="initMap">重试</button>
      </view>
    </view>
    
    <!-- 添加POI按钮 -->
    <view class="add-poi-btn" @click="showAddPOIForm">
      <text class="btn-icon">+</text>
    </view>
    
    <!-- 添加POI表单 -->
    <view class="poi-form-modal" v-if="showPOIForm">
      <view class="form-header">
        <text class="form-title">{{ isEditing ? '编辑POI点位' : '添加POI点位' }}</text>
        <text class="close-btn" @click="closePOIForm">×</text>
      </view>
      
      <view class="form-content">
        <view class="form-item">
          <text class="form-label">名称</text>
          <input type="text" class="form-input" v-model="poiForm.name" placeholder="请输入POI名称" />
        </view>
        
        <view class="form-item">
          <text class="form-label">类型</text>
          <picker 
            class="form-picker" 
            :range="poiTypeOptions" 
            range-key="name" 
            @change="handleTypeChange"
          >
            <view class="picker-text">{{ getSelectedTypeName() }}</view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="form-label">详情</text>
          <textarea class="form-textarea" v-model="poiForm.details" placeholder="请输入详细信息"></textarea>
        </view>
        
        <view class="form-item">
          <text class="form-label">位置</text>
          <view class="location-display">
            <text class="location-text">{{ poiForm.address || '点击地图选择位置' }}</text>
          </view>
        </view>
        
        <view class="form-item" v-if="poiForm.type === 'facility'">
          <text class="form-label">无障碍设施详情</text>
          <view class="detail-form">
            <view class="detail-item">
              <text class="detail-label">门宽(cm)</text>
              <input type="number" class="detail-input" v-model="poiForm.facilityDetails.doorWidth" />
            </view>
            <view class="detail-item">
              <text class="detail-label">是否有坡道</text>
              <switch :checked="poiForm.facilityDetails.hasRamp" @change="e => poiForm.facilityDetails.hasRamp = e.detail.value" />
            </view>
          </view>
        </view>
      </view>
      
      <view class="form-actions">
        <button class="cancel-btn" @click="closePOIForm">取消</button>
        <button class="save-btn" @click="savePOI">保存</button>
      </view>
    </view>
  </view>
</template>

<script>
import POISearch from '@/components/POISearch.vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import { usePOIStore } from '@/store/poiStore';
import { storeToRefs } from 'pinia';

export default {
  components: {
    POISearch
  },
  
  setup() {
    const poiStore = usePOIStore();
    const { pois } = storeToRefs(poiStore);
    
    return {
      poiStore,
      pois
    };
  },
  
  data() {
    return {
      map: null,
      isMapLoaded: false,
      mapError: '',
      markers: [],
      searchResults: [],
      selectedPOI: null,
      showPOIForm: false,
      isEditing: false,
      clickedPosition: null,
      poiForm: {
        name: '',
        type: 'facility',
        details: '',
        address: '',
        location: null,
        facilityDetails: {
          doorWidth: 90,
          hasRamp: false
        }
      },
      poiTypeOptions: [
        { value: 'facility', name: '无障碍设施' },
        { value: 'toilet', name: '无障碍卫生间' },
        { value: 'elevator', name: '无障碍电梯' },
        { value: 'parking', name: '爱心停车位' },
        { value: 'restaurant', name: '餐饮' },
        { value: 'shopping', name: '购物' },
        { value: 'hospital', name: '医疗' },
        { value: 'other', name: '其他' }
      ]
    };
  },
  
  computed: {
    // 获取自定义POI数据供搜索组件使用
    customPOIs() {
      return this.pois || [];
    }
  },
  
  onLoad() {
    // 设置安全密钥
    window._AMapSecurityConfig = {
      securityJsCode: '1b60a36d751dcf1e93a2975d4908982e' // 应替换为您自己的安全密钥
    };
    
    // 初始化高德地图
    this.initMap();
    
    // 初始化POI数据
    this.poiStore.initPOIs();
  },
  
  onUnload() {
    // 销毁地图实例
    if (this.map) {
      this.map.destroy();
      this.map = null;
    }
  },
  
  methods: {
    // 返回首页地图页面
    goBack() {
      uni.navigateBack({
        success: () => {
          console.log('返回首页成功');
        },
        fail: () => {
          // 如果返回失败，直接跳转到首页
          uni.switchTab({
            url: '/pages/index/index',
            success: () => {
              console.log('跳转到首页成功');
            },
            fail: (err) => {
              console.error('跳转到首页失败:', err);
            }
          });
        }
      });
    },
    
    // 初始化地图
    async initMap() {
      try {
        // 加载高德地图
        const AMap = await AMapLoader.load({
          key: '79f4d4eb1ed11f2b0ac4f1065c0788da', // 应替换为您自己的API密钥
          version: '2.0',
          plugins: ['AMap.PlaceSearch', 'AMap.Geocoder', 'AMap.Scale', 'AMap.ToolBar']
        });
        
        // 创建地图实例
        this.map = new AMap.Map('mapContainer', {
          zoom: 13,
          center: [116.397428, 39.90923],
          viewMode: '3D'
        });
        
        // 添加控件
        this.map.addControl(new AMap.Scale());
        this.map.addControl(new AMap.ToolBar());
        
        // 添加地图点击事件
        this.map.on('click', (e) => {
          if (this.showPOIForm) {
            // 如果表单已打开，则更新位置
            this.clickedPosition = {
              lng: e.lnglat.getLng(),
              lat: e.lnglat.getLat()
            };
            this.getAddressByLocation(this.clickedPosition);
          } else {
            // 否则显示POI添加表单
            this.clickedPosition = {
              lng: e.lnglat.getLng(),
              lat: e.lnglat.getLat()
            };
            this.showAddPOIForm();
            this.getAddressByLocation(this.clickedPosition);
          }
        });
        
        this.isMapLoaded = true;
        this.mapError = '';
        
        // 显示已有的自定义POI
        this.showCustomPOIs();
        
      } catch (error) {
        console.error('地图初始化失败:', error);
        this.mapError = `地图加载失败: ${error.message || '未知错误'}`;
        this.isMapLoaded = false;
      }
    },
    
    // 根据位置获取地址
    getAddressByLocation(location) {
      if (!this.map || !location) return;
      
      const geocoder = new window.AMap.Geocoder();
      geocoder.getAddress([location.lng, location.lat], (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          const address = result.regeocode.formattedAddress;
          this.poiForm.address = address;
          this.poiForm.location = location;
        } else {
          this.poiForm.address = '未知位置';
          this.poiForm.location = location;
        }
      });
    },
    
    // 显示添加POI表单
    showAddPOIForm() {
      this.isEditing = false;
      this.poiForm = {
        name: '',
        type: 'facility',
        details: '',
        address: '',
        location: this.clickedPosition,
        facilityDetails: {
          doorWidth: 90,
          hasRamp: false
        }
      };
      this.showPOIForm = true;
    },
    
    // 关闭POI表单
    closePOIForm() {
      this.showPOIForm = false;
    },
    
    // 处理类型变更
    handleTypeChange(e) {
      const index = e.detail.value;
      this.poiForm.type = this.poiTypeOptions[index].value;
    },
    
    // 获取当前选中的类型名称
    getSelectedTypeName() {
      const selectedType = this.poiTypeOptions.find(option => option.value === this.poiForm.type);
      return selectedType ? selectedType.name : '请选择类型';
    },
    
    // 保存POI
    savePOI() {
      if (!this.validatePOIForm()) return;
      
      if (this.isEditing) {
        // 更新现有POI
        const result = this.poiStore.updatePOI(this.selectedPOI.id, {
          name: this.poiForm.name,
          type: this.poiForm.type,
          details: this.poiForm.details,
          address: this.poiForm.address,
          location: this.poiForm.location,
          facilityDetails: this.poiForm.type === 'facility' ? this.poiForm.facilityDetails : null
        });
        
        if (result) {
          uni.showToast({
            title: 'POI更新成功',
            icon: 'success'
          });
        } else {
          uni.showToast({
            title: 'POI更新失败',
            icon: 'none'
          });
        }
      } else {
        // 添加新POI
        const result = this.poiStore.addPOI({
          name: this.poiForm.name,
          type: this.poiForm.type,
          details: this.poiForm.details,
          address: this.poiForm.address,
          location: this.poiForm.location,
          facilityDetails: this.poiForm.type === 'facility' ? this.poiForm.facilityDetails : null
        });
        
        if (result) {
          uni.showToast({
            title: 'POI添加成功',
            icon: 'success'
          });
        } else {
          uni.showToast({
            title: 'POI添加失败',
            icon: 'none'
          });
        }
      }
      
      // 更新地图上的标记
      this.showCustomPOIs();
      
      // 关闭表单
      this.closePOIForm();
    },
    
    // 验证POI表单
    validatePOIForm() {
      if (!this.poiForm.name.trim()) {
        uni.showToast({
          title: '请输入POI名称',
          icon: 'none'
        });
        return false;
      }
      
      if (!this.poiForm.location) {
        uni.showToast({
          title: '请选择POI位置',
          icon: 'none'
        });
        return false;
      }
      
      return true;
    },
    
    // 在地图上显示自定义POI
    showCustomPOIs() {
      if (!this.map || !this.isMapLoaded) return;
      
      // 清除现有标记
      this.clearMarkers();
      
      // 添加新标记
      if (this.pois) {
        this.pois.forEach(poi => {
          if (poi.location) {
            const marker = new window.AMap.Marker({
              position: [poi.location.lng, poi.location.lat],
              title: poi.name,
              clickable: true
            });
            
            marker.on('click', () => {
              this.selectPOI(poi);
            });
            
            marker.setMap(this.map);
            this.markers.push(marker);
          }
        });
      }
    },
    
    // 清除所有标记
    clearMarkers() {
      if (this.markers.length > 0) {
        this.markers.forEach(marker => {
          marker.setMap(null);
        });
        this.markers = [];
      }
    },
    
    // 处理选择POI
    handleSelectPOI(poi) {
      this.selectPOI(poi);
    },
    
    // 选择POI
    selectPOI(poi) {
      this.selectedPOI = poi;
      
      // 如果是官方POI，仅显示详情并将地图中心移到该位置
      if (poi.isOfficial) {
        // 移动地图中心
        this.map.setCenter([poi.location.lng, poi.location.lat]);
        
        // 显示信息窗口
        const infoWindow = new window.AMap.InfoWindow({
          content: `<div class="info-window">
            <h3>${poi.name}</h3>
            <p>${poi.address}</p>
          </div>`,
          offset: new window.AMap.Pixel(0, -30)
        });
        
        infoWindow.open(this.map, [poi.location.lng, poi.location.lat]);
      } else {
        // 如果是自定义POI，记录查看并显示详情
        if (poi.id) {
          this.poiStore.addRecentViewed(poi.id);
        }
        
        // 移动地图中心
        this.map.setCenter([poi.location.lng, poi.location.lat]);
        
        // 显示信息窗口
        const infoWindow = new window.AMap.InfoWindow({
          content: this.createInfoWindowContent(poi),
          offset: new window.AMap.Pixel(0, -30)
        });
        
        infoWindow.open(this.map, [poi.location.lng, poi.location.lat]);
      }
    },
    
    // 创建信息窗口内容
    createInfoWindowContent(poi) {
      let content = `<div class="info-window">
        <h3>${poi.name}</h3>
        <p>${poi.address || '未知地址'}</p>`;
        
      if (poi.details) {
        content += `<p class="details">${poi.details}</p>`;
      }
      
      if (poi.facilityDetails) {
        content += '<div class="facility-details">';
        
        if (poi.facilityDetails.doorWidth) {
          content += `<p>门宽: ${poi.facilityDetails.doorWidth}cm</p>`;
        }
        
        if (typeof poi.facilityDetails.hasRamp !== 'undefined') {
          content += `<p>有无坡道: ${poi.facilityDetails.hasRamp ? '有' : '无'}</p>`;
        }
        
        content += '</div>';
      }
      
      // 添加编辑和删除按钮
      content += `<div class="info-buttons">
        <button onclick="window.poiEditCallback('${poi.id}')">编辑</button>
        <button onclick="window.poiDeleteCallback('${poi.id}')">删除</button>
      </div>`;
      
      content += '</div>';
      
      // 注册回调函数
      window.poiEditCallback = (id) => {
        this.editPOI(this.poiStore.getPOIById(id));
      };
      
      window.poiDeleteCallback = (id) => {
        this.deletePOI(id);
      };
      
      return content;
    },
    
    // 编辑POI
    editPOI(poi) {
      if (!poi) return;
      
      this.isEditing = true;
      this.selectedPOI = poi;
      
      this.poiForm = {
        name: poi.name,
        type: poi.type,
        details: poi.details || '',
        address: poi.address || '',
        location: poi.location,
        facilityDetails: poi.facilityDetails || {
          doorWidth: 90,
          hasRamp: false
        }
      };
      
      this.showPOIForm = true;
    },
    
    // 删除POI
    deletePOI(id) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除此POI吗？',
        success: (res) => {
          if (res.confirm) {
            const result = this.poiStore.deletePOI(id);
            
            if (result) {
              this.showCustomPOIs();
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              });
            } else {
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              });
            }
          }
        }
      });
    },
    
    // 处理搜索完成
    handleSearchComplete(results) {
      this.searchResults = results;
      
      // 清除所有标记
      this.clearMarkers();
      
      // 添加搜索结果标记
      results.forEach(poi => {
        if (poi.location) {
          const marker = new window.AMap.Marker({
            position: [poi.location.lng, poi.location.lat],
            title: poi.name,
            clickable: true
          });
          
          marker.on('click', () => {
            this.selectPOI(poi);
          });
          
          marker.setMap(this.map);
          this.markers.push(marker);
        }
      });
      
      // 如果有结果，调整地图视野
      if (results.length > 0) {
        this.fitMapToMarkers();
      }
    },
    
    // 调整地图视野以包含所有标记
    fitMapToMarkers() {
      if (this.markers.length === 0) return;
      
      const bounds = new window.AMap.Bounds();
      this.markers.forEach(marker => {
        bounds.extend(marker.getPosition());
      });
      
      this.map.setBounds(bounds);
    }
  }
};
</script>

<style>
.poi-map-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  position: relative;
}

.map-wrap {
  flex: 1;
  position: relative;
}

.map-container {
  width: 100%;
  height: 100%;
}

.map-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
}

.loading-text {
  font-size: 32rpx;
  color: #666;
}

.map-error {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 30rpx;
}

.error-text {
  font-size: 28rpx;
  color: #ff5151;
  margin-bottom: 30rpx;
  text-align: center;
}

.retry-btn {
  font-size: 28rpx;
  padding: 10rpx 40rpx;
  background-color: #3F7BFC;
  color: #fff;
  border-radius: 30rpx;
}

.add-poi-btn {
  position: absolute;
  right: 30rpx;
  bottom: 100rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: #3F7BFC;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4rpx 16rpx rgba(63, 123, 252, 0.4);
  z-index: 10;
}

.btn-icon {
  font-size: 48rpx;
}

.poi-form-modal {
  position: absolute;
  left: 50rpx;
  right: 50rpx;
  top: 50%;
  transform: translateY(-50%);
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.2);
  z-index: 100;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1px solid #f0f2f5;
}

.form-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  font-size: 40rpx;
  color: #999;
}

.form-content {
  padding: 30rpx;
  max-height: 700rpx;
  overflow-y: auto;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.form-input, .form-picker, .location-display {
  width: 100%;
  height: 80rpx;
  border: 1px solid #ddd;
  border-radius: 10rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  background-color: #fff;
}

.form-textarea {
  width: 100%;
  height: 200rpx;
  border: 1px solid #ddd;
  border-radius: 10rpx;
  padding: 20rpx;
  font-size: 28rpx;
  background-color: #fff;
}

.picker-text {
  height: 80rpx;
  line-height: 80rpx;
}

.location-display {
  display: flex;
  align-items: center;
}

.location-text {
  font-size: 28rpx;
  color: #333;
}

.detail-form {
  padding: 20rpx;
  background-color: #f9fafc;
  border-radius: 10rpx;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.detail-label {
  font-size: 28rpx;
  color: #666;
}

.detail-input {
  width: 200rpx;
  height: 60rpx;
  border: 1px solid #ddd;
  border-radius: 6rpx;
  padding: 0 10rpx;
  font-size: 28rpx;
  background-color: #fff;
}

.form-actions {
  display: flex;
  padding: 20rpx 30rpx;
  border-top: 1px solid #f0f2f5;
}

.cancel-btn, .save-btn {
  flex: 1;
  margin: 0 10rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.save-btn {
  background-color: #3F7BFC;
  color: #fff;
}

/* 返回按钮样式 */
.back-btn {
  position: absolute;
  left: 20rpx;
  top: 150rpx;
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.back-btn .icon-back {
  font-size: 36rpx;
  color: #333;
}
</style> 